#include "cfactory.hpp"
void epoll_func(int epfd, int fd, int caozuo, int duxie)
{
    struct epoll_event event;
    event.data.fd = fd;
    event.events = duxie;
    epoll_ctl(epfd, caozuo, fd, &event);
}
int recvCYL(int fd, void *pbuf, int len)
{
    char *buf = (char *)pbuf;
    int total = 0, ret = 0;
    while (total < len)
    {
        ret = recv(fd, buf + total, len - total, 0);
        if (ret == 0)
        {
            return -1;
        }
        total += ret;
    }
    return 0;
}
int one_recv(int fd, Train_t *ptrain)
{
    int ret = recvCYL(fd, &ptrain->len, 4);
    if (ret == -1)
        return -1;
    ret = recvCYL(fd, &ptrain->ctl_code, 4);
    if (ret == -1)
        return -1;
    if (ptrain->len == 0)
    {
        return 0;
    }
    ret = recvCYL(fd, &ptrain->buf, ptrain->len);
    if (ret == -1)
        return -1;
    return 0;
}
void ssend(int *cFd, int epfd, Train_t *ptrain)
{
    int ret = send(*cFd, ptrain, ptrain->len + 8, 0);
    if (ret == -1)
    {
        Train_t new_train;
        memcpy(&new_train, ptrain, 8 + ptrain->len);
        epoll_func(epfd, *cFd, EPOLL_CTL_DEL, EPOLLIN);
        close(*cFd);
        *cFd = socket(AF_INET, SOCK_STREAM, 0);
        ret = connect(*cFd, (struct sockaddr *)&ser, sizeof(ser));
        epoll_func(epfd, *cFd, EPOLL_CTL_ADD, EPOLLIN);
        ptrain->len = sizeof(Zhuce);
        memcpy(ptrain->buf, &login_msg, ptrain->len);
        ptrain->ctl_code = TOKEN_PLESE;
        ret = send(*cFd, ptrain, 8 + ptrain->len, 0);
        ret = send(*cFd, &new_train, 8 + new_train.len, 0);
    }
}